unit main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, com, StdCtrls, common, ExtCtrls, ImgList;


type
  TfrmMain = class(TForm)
    memodbg: TMemo;
    ImageListLED: TImageList;
    RxLEDTimer: TTimer;
    imgRxLED: TImage;
    procedure FormCreate(Sender: TObject);
    procedure OnMessage(var Msg: TMessage); message WM_MESSAGE_MAINFORM;
    procedure RxLEDTimerTimer(Sender: TObject);
  private
    { Private declarations }
    AppLog : TextFile;


    connected : boolean;
  public
    { Public declarations }
    WinMsg : T_MESSAGE_DATA;
    pkt : T_PACKET;

    function DecodePacket(instr : string) : boolean;
    procedure Log(str : string);
    procedure RxLED(state : boolean);
  end;

var
  frmMain: TfrmMain;
  cp : TcomProtocol;
implementation

{$R *.dfm}

uses ZylSerialPort;

procedure TfrmMain.OnMessage(var Msg: TMessage);
var
  t : integer;
  str : string;

begin
  if  winmsg.destination = MESS_PACKET then
	begin
    str := '';
    for t := 1 to length(winmsg.dataStr) do
    begin
      str := str + inttohex(integer(winmsg.dataStr[t]),2) + ' ';
    end;
    //memodbg.Text := str;
    write(AppLog, str + CRLF);

    DecodePacket(winmsg.dataStr);
    memodbg.Text :=  'ID: ' + pkt.id + ' RSSI: ' + inttostr(pkt.rssi) + CRLF;

    RxLED(true);
    RxLEDTimer.Enabled := true;

  end;
end;

procedure TfrmMain.RxLED(state: boolean);
var
  Icon : TIcon;
begin
  Icon := TIcon.Create;
  if state then
    ImageListLED.GetIcon(1, Icon)   // Led On
  else
    ImageListLED.GetIcon(0, Icon);   // Led Off

  imgRxLed.Picture.Icon := Icon;
  FreeAndNIl(Icon);
end;

procedure TfrmMain.RxLEDTimerTimer(Sender: TObject);
begin
 RxLED(False);
 RxLEDTimer.Enabled := false;
end;

function TfrmMain.DecodePacket(instr : string) : boolean;

begin
  result := true;

  // Get ID string
  pkt.id :=
    inttohex(integer(instr[PACKET_OFFSET_ID+0]),2) +
    inttohex(integer(instr[PACKET_OFFSET_ID+1]),2) +
    inttohex(integer(instr[PACKET_OFFSET_ID+2]),2) +
    inttohex(integer(instr[PACKET_OFFSET_ID+3]),2);
  pkt.rssi :=
    integer( instr[PACKET_OFFSET_RSSI+0]) shl 8 +
    integer( instr[PACKET_OFFSET_RSSI+1]) shl 0;

end;

procedure TfrmMain.FormCreate(Sender: TObject);
begin

  AssignFile(AppLog, 'MyPCSecurity.log');

  try
    ReWrite(AppLog);
  except
    MessageDlg('Unable to create an app log.', mtInformation, [mbOk], 0, mbOk);
  end;
  connected := true;

  cp := TComProtocol.Create(self);
  cp.mComPort := spCOM34;

  //comPorts := frmComProtocol.GetExistingCommPorts();
  if cp.SerConnect then
    memodbg.Text := 'Connected to Receiver' + CRLF;

  RxLED(false);

end;

procedure TfrmMain.Log(str: string);
begin
  write(AppLog, str);
  system.flush(AppLog);
end;

end.
